<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--产品数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入产品名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--产品详情数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
              <el-form-item label="产品详情名称" prop="detailTitle">
                <!-- <el-input v-model="queryParams.userName" placeholder="请输入产品详情名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" /> -->
                <el-select v-model="queryParams.detailTitle" placeholder="产品详情名称" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.detail_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="产品详情状态" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item> -->
              <el-form-item label="创建时间">
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="产品详情名称" align="center" prop="detailTitle">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.detail_type" :value="scope.row.detailTitle"/>
                </template>
              </el-table-column>
              <!-- <el-table-column label="产品详情名称" align="center" prop="detailTitle" :show-overflow-tooltip="true" /> -->

              <el-table-column label="归属产品" align="center" prop="productId">
                <template slot-scope="scope">
                    {{ treeList.find(item=>item.productId===scope.row.productId).productName }}
                </template>
              </el-table-column>

              <!-- <el-table-column label="状态" align="center" key="status">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column> -->
              <el-table-column label="顺序" align="center" prop="orderNum"/>
              <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                  <el-button size="mini" type="text" icon="el-icon-view" @click="handleJump(scope.row)">配置</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改产品详情配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="详情名称" prop="detailTitle">
              <!-- <el-input v-model="form.detailTitle" placeholder="请输入详情名称" maxlength="30" /> -->
              <el-select v-model="form.detailTitle" placeholder="产品详情名称" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.detail_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属产品" prop="productId">
              <treeselect v-model="form.productId" :options="deptOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择归属产品" style="width: 240px;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" style="width: 240px;"/>
              </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="Number(dict.value) ">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUser, delDetail, addDetail, updateDetail, changeUserStatus, listDept,listDetails } from "@/api/official/bookList";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "BookDetails",
  dicts: ['detail_type','sys_normal_disable'],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品详情表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 产品树选项
      deptOptions: undefined,
      treeList:[],
      // 是否显示弹出层
      open: false,
      // 产品名称
      deptName: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "productName"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        productId: undefined,
        detailTitle:'',
        isAsc: "asc",
        orderByColumn: "orderNum",
      },
      // 列信息
      columns: [
        { key: 0, label: `产品详情编号`, visible: true },
        { key: 1, label: `产品详情名称`, visible: true },
        { key: 2, label: `产品详情昵称`, visible: true },
        { key: 3, label: `产品`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "产品详情名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '产品详情名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "产品详情昵称不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选产品树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询产品详情列表 */
    getList() {
      this.loading = true;
      listDetails(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.productId,
        label: node.productName,
        children: node.children
      };
    },
    /** 查询产品下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.treeList = [...response.data];
        this.deptOptions = this.handleTree(response.data, "productId");
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data,node) {
      console.log('data',data);
      console.log('node',node);
      this.queryParams.productId = data.productId;
      if(node.isLeaf){
        this.handleQuery();
      }
    },
    // 产品详情状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"产品详情吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: undefined,
        detailTitle: undefined,
        // status: "0",
        orderNum: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.productId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.detailId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.form = {...row};
      console.log('this.form', this.form);
      this.open = true;
      this.title = "修改产品详情";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.detailId != undefined) {
            console.log('this.form',this.form);
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const detailId = row.detailId || this.ids;
      this.$modal.confirm('是否确认删除产品详情编号为"' + detailId + '"的数据项？').then(function() {
        return delDetail(detailId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleJump(row){
      console.log('row',row);
      const detailOne = this.dict.type.detail_type.find(item=>item.value===row.detailTitle).label;
      const productName = this.treeList.find(item=>item.productId===row.productId).productName;
      // this.$router.push("/official/user-auth/role/" + userId);
      this.$router.push({ path: "/official/book/bookSet/" , query: {detailId:row.detailId,productId:row.productId,detailOne:detailOne,productName:productName} });
    }
  }
};
</script>
